package com.briup.pai.interceptor;

import com.briup.pai.common.constant.LoginConstant;
import com.briup.pai.common.enums.ResultCodeEnum;
import com.briup.pai.common.exception.BriupAssert;
import com.briup.pai.common.exception.CustomException;
import com.briup.pai.common.utils.JwtUtil;
import com.briup.pai.common.utils.SecurityUtil;
import io.jsonwebtoken.ExpiredJwtException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * ClassName：LoginInterceptor
 *
 * @Author：小鱼
 * @Create：2025-10-28 14:52
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是请求处理器方法，直接放行
        if(request.getMethod().equalsIgnoreCase("options")){
            return true;
        }
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // 请求头中没有token
        String token = request.getHeader(LoginConstant.TOKEN_NAME);
        //验证token有效性
        try {
            BriupAssert.requireNotNull(
                    token,
                    ResultCodeEnum.USER_NOT_LOGIN
            );
        } catch (ExpiredJwtException e) {
            throw new CustomException(ResultCodeEnum.USER_LOGIN_EXPIRATION);
        }
        // 获取用户ID
        Integer userId = JwtUtil.getUserId(token);
        // 放到ThreadLocal中
        SecurityUtil.setUserId(userId);
        // 放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 删除ThreadLocal中的数据，避免内存泄漏
        SecurityUtil.removeUserId();
    }

}
